<?php
/**
 * Created by PhpStorm.
 * User: skytop
 * Date: 2016/7/19
 * Time: 19:23
 */

namespace Admin\Controller;


use Admin\Model\Captcha;
use Think\Controller;

class LoginController extends Controller
{

    /*
     * 登录
     * */
    public function index(){
        if(!IS_POST) {
            $this->display();
        }else{
            /*dump(I('post.'));*/
            if(Captcha::checkCaptcha(I('post.code'),Captcha::LOGIN_CAPTCHA)){
                $username=I('post.username');
                $password=I('post.password','','md5');
                $logintime=time();
                $loginip=get_client_ip();

                $save=array(
                    'logintime'=>$logintime,
                    'loginip'=>$loginip
                );

                $userTable=M('user');

                $where=array(
                    'username'=>$username,
                    'password'=>$password
                );
                if($userTable->where($where)->count()){

                    $pasttime=$userTable->where($where)->getField('logintime');
                    $Lasttime=date('m-d H:i',$pasttime);
                    session('pasttime',$Lasttime);

                    $userTable->where($where)->save($save);

                    session('loginUser',$username);
                    $this->success('登录成功',U('Index/index'));
                }else{
                    $this->error('用户名或密码输入错误',U('Login/index'));
                }
            }else{
                $this->error('验证码错误',U('Login/index'));
            }
        }
    }

    /*
     * 注销
     * */
    public function logout(){
        session('loginUser',null);
        session('pasttime',null);
        $this->success('注销成功正在返回登录页面',U('Login/index'));
    }

    /**
     * 验证码
     * @param string $atype
     */
    public function captcha($atype='register'){
        switch($atype){
            case 'register':
                Captcha::createCaptcha(Captcha::REGISTER_CAPTCHA);
                break;
            case 'login':
                Captcha::createCaptcha(Captcha::LOGIN_CAPTCHA);
                break;
            default:
                Captcha::createCaptcha(Captcha::REGISTER_CAPTCHA);
                break;
        }
    }
}